<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>12_随机验证码校验</title>
    <style type="text/css">
        #code{
            width: 100px;
            height: 100px;
            background-color: #ddd;
            padding: 10px;
            line-height: 100px;
            text-align: center;
            font-size: 20px;
            color: red;
            font-weight: bold;
        }
        input{
            outline: none;
        }

    </style>
</head>
<body>
    <div id="code"></div>
    <input type="text" name="" id="newCode">
    <input type="button" name="" id="validate" value="验证">

    <script type="text/javascript">

        window.onload = function(){
            // 保存全局, 与新输入的验证码进行校验
            var code;
            // 1.获取对应的标签
            var codeDiv = document.getElementById('code');
            var newCodeInput = document.getElementById('newCode');
            var validate = document.getElementById('validate');
            // 加载页面获取对应的验证码
            creatCode()
            // 1.获取min到max之间的整数(1~100)
            function random(max,min){
                return Math.floor(Math.random() * (max-min) + min);
            }
            function creatCode(){
                // 设置默认的空的字符串
                code = '';
                // 设置长度
                var codeLength = 4;
                var randomCode = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
                for(var i = 0; i < codeLength; i++){
                    // 设置随机范围0~36
                    var index = random(0,36);
                    code += randomCode[index];
                }
                codeDiv.innerHTML = code;
            }
            // 验证按钮校验
            validate.onclick = function(){
                // 获取用户新输入的验证码
                var newCode = newCodeInput.value.toUpperCase();
                if(newCode === code){
                    // 验证成功 跳转对应的网址
                    window.location.href = 'https://www.apeland.cn';
                }else{
                    // 验证失败
                    alert('验证码不正确,请重新输入');
                    // 输入框置空
                    newCodeInput.value = '';
                    // 重新获取验证码
                    creatCode();

                }
            }
        }

    </script>
</body>
</html>